package es.abredatos.client.presenter;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerManager;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HasText;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Widget;

import es.abredatos.client.BooksLocatorServiceAsync;
import es.abredatos.client.event.LocateLibraryEvent;
import es.abredatos.shared.Book;

public class BookPresenter implements Presenter {

	public interface Display {
		HasText getBookTitle();

		HasText getBookDescription();

		HasClickHandlers getLibrariesButton();
	}

	private BooksLocatorServiceAsync rpcService;
	private HandlerManager eventBus;
	private Display display;
	private String id;

	public BookPresenter(BooksLocatorServiceAsync rpcService, HandlerManager eventBus, Display display, String id) {
		this.rpcService = rpcService;
		this.eventBus = eventBus;
		this.display = display;
		this.id = id;
	}

	public void go(HasWidgets container) {
		container.clear();
		container.add((Widget) display);

		bind();

		fetchBookDetails(id);
	}

	private void bind() {
		display.getLibrariesButton().addClickHandler(new ClickHandler() {

			public void onClick(ClickEvent event) {
				eventBus.fireEvent(new LocateLibraryEvent("0"));
			}
		});
	}

	private void fetchBookDetails(String id) {
		rpcService.getBookDetails(id, new AsyncCallback<Book>() {

			public void onSuccess(Book book) {
				display.getBookTitle().setText(book.getTitle());
				display.getBookDescription().setText(book.getDescription());
			}

			public void onFailure(Throwable caught) {
				Window.alert("Communication fal");
			}
		});
	}

}
